package backtrace;

public class leetcode79单词搜索 {
    public boolean exist(char[][] board, String word) {
        int row = board.length;
        int col = board[0].length;
        boolean[][] visited = new boolean[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == word.charAt(0)) {
                    fillFalse(visited);
                    if(dfs(board, visited, i, j, word, 0)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public void fillFalse(boolean[][] visited) {
        for (int i = 0; i < visited.length; i++) {
            for (int j = 0; j < visited[0].length; j++) {
                visited[i][j] = false;
            }
        }
    }

    public boolean dfs(char[][] board, boolean[][] visited, int x, int y, String word, int index) {
        if (index == word.length()) {
            return true;
        }
        if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || board[x][y] != word.charAt(index) || visited[x][y]) {
            return false;
        }
        visited[x][y] = true;
        boolean isTrue =
                dfs(board, visited, x - 1, y, word, index + 1)
                || dfs(board, visited, x, y + 1, word, index + 1)
                || dfs(board, visited, x + 1, y, word, index + 1)
                || dfs(board, visited, x, y - 1, word, index + 1);
        visited[x][y] = false;
        return isTrue;
    }
}
